package com.tm.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Rocky
 * @create 2022-09-21 20:01
 */
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter{

    @Autowired
    private RedisTemplate redisTemplate;

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();

        RequestPath path = request.getPath();

        if (path.toString().contains("/login/sendCode" )||path.toString().contains("/login/addUser" )){
            return chain.filter(exchange);
        }

        //2.获取参数中的authorization参数
        String phonenumber = queryParams.getFirst("phonenumber");
        String userToken = queryParams.getFirst("userToken");
        Object o = redisTemplate.opsForValue().get("token_" + phonenumber);
        //3,判断参数值是否等于admin
        if (o!=null && o.toString().equals(userToken)){
            //有的话 放行
            return chain.filter(exchange);
        }
        //设置状态吗
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        //4.否 拦截
        return exchange.getResponse().setComplete();
    }




}
